var express = require('express');
var router = express.Router();
const userModel = require('../model/users');
const sha1 = require('sha1')
var multer  = require('multer')

var upload = multer({ dest: 'uploads/' })
// var upload = multer()
// const upload = require('./model/file');
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/node', function(req, res, next) {
  res.render('node', { title: 'Node' });
});
/**
 * 查询列表
 */
router.get('/userLists', function(req, res, next) {
  userModel.userLists(req,res,next)
});


/**
 * 上传文件
 */
var cpUpload = upload.fields([{ name: 'upload_file', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
router.post('/profile', cpUpload, function (req, res, next) {
    // req.file 是 `avatar` 文件的信息
    // req.body 将具有文本域数据，如果存在的话
  
    // upload(req, res, function (err) {
    //     if (err) {
    //       // 发生错误
    //       console.info(err)
    //       return
    //     }
        // console.log(req.file)
        // console.log(req.body)
        res.status(200)
        res.json({
          code:0,
          data:{
            aaa:1
          }
        })
        // res.render('index', { title: '上传成功' });  
        // 一切都好
      // })

  })

  

  var createNonceStr = function () {
    return Math.random().toString(36).substr(2, 15);
  };
  
  var createTimestamp = function () {
    return parseInt(new Date().getTime() / 1000) + '';
  };
const aaa  = require('../common/aaa');
console.log(aaa.b)


  router.post('/wxJssdk/getJssdk', (req, res) => {
    console.log(req.body.url)
    const request = require('request')
   
    const grant_type = 'client_credential'
    const appid = 'wx0e4a98dfeedc3dbc'
    const secret = '254398e3f7ff0878911fcba5d7a0de0c'

    request('https://api.weixin.qq.com/cgi-bin/token?grant_type=' + grant_type + '&appid=' + appid + '&secret=' + secret, (err, response, body) => {
      let access_token = JSON.parse(body).access_token
      aaa.b = access_token;
      request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + access_token + '&type=jsapi', (err, response, body) => {
         let jsapi_ticket = JSON.parse(body).ticket
         let nonce_str = createNonceStr()    // 密钥，字符串任意，可以随机生成
         let timestamp = createTimestamp()  // 时间戳
         let url = req.body.url   // 使用接口的url链接，不包含#后的内容
         console.log(url)
   
         // 将请求以上字符串，先按字典排序，再以'&'拼接，如下：其中j > n > t > u，此处直接手动排序
         let str = 'jsapi_ticket=' + jsapi_ticket + '&noncestr=' + nonce_str + '&timestamp=' + timestamp + '&url=' + url
          console.log(str)
         // 用sha1加密
         let signature = sha1(str)
   
         res.send({
           appId: appid,
           timestamp: timestamp,
           nonceStr: nonce_str,
           signature: signature
         })
      })
    })
  })  


module.exports = router;
